package com.fh.shop.admin.biz.area;

import com.fh.shop.admin.common.ServerResponse;
import com.fh.shop.admin.mapper.area.IAreaMapper;
import com.fh.shop.admin.vo.area.AreaVo;
import com.fh.shop.admin.po.area.Area;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("areaService")
public class IAreaServiceImpl implements IAreaService {
    @Autowired
    private IAreaMapper areaMapper;

    //查询
    @Override
    public ServerResponse findAreaList() {
        //查询所有数据
        List<Area> areaList = areaMapper.findAreaList();
        //存放前台需要的参数类型
        List<AreaVo> areaVoList = new ArrayList<>();
        for (Area area : areaList) {
            AreaVo areaVo = buildArea(area);
            areaVoList.add(areaVo);
        }
        return ServerResponse.success(areaVoList);
    }


    //新增
    @Override
    public ServerResponse addArea(Area area) {
        areaMapper.addArea(area);
        AreaVo areaVo = buildArea(area);
        return ServerResponse.success(areaVo);
    }

    private AreaVo buildArea(Area area) {
        AreaVo areaVo = new AreaVo();
        areaVo.setId(area.getId());
        areaVo.setpId(area.getFatherId());
        areaVo.setName(area.getAreaName());
        return areaVo;
    }

    //删除
    @Override
    public ServerResponse deleteBatchArea(String ids) {
        if (StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            List<Long> idList = new ArrayList<>();
            for (String s : idArr) {
                idList.add(Long.parseLong(s));
            }
            areaMapper.deleteBatchArea(idList);
        }
        return ServerResponse.success();
    }

    //回显
    @Override
    public ServerResponse findArea(Long id) {
        Area area = areaMapper.findArea(id);
        return ServerResponse.success(area);
    }

    //修改
    @Override
    public ServerResponse updateArea(Area area) {
        areaMapper.updateArea(area);
        return ServerResponse.success();
    }

    //根据父级id查询省市区
    @Override
    public ServerResponse findAreaByFatherId(Long id) {
        List<Area> areaList = areaMapper.findAreaByFatherId(id);
        return ServerResponse.success(areaList);
    }

}
